package org.df.ulab.bot.redmine.command;

import org.df.ulab.bot.api.command.CommandFactory;
import org.df.ulab.bot.api.command.InitializationRequired;
import org.df.ulab.bot.api.pmi.entity.Member;
import org.df.ulab.bot.plugins.pmi.HandlerSession;
import org.df.ulab.bot.plugins.pmi.command.GenCommitWork;
import org.df.ulab.bot.plugins.pmi.commons.DefaultTimeEntry;
import org.df.ulab.bot.plugins.pmi.commons.PmiDatabase;
import org.df.ulab.bot.util.message.BasicMsgInterpreter;

/**
 * @author Daniel Filgueiras
 * 04/05/2011
 */
@CommandFactory(BasicMsgInterpreter.class)
@InitializationRequired
public class DbCommitWork extends GenCommitWork  {

	@Override
	protected boolean commit() {
		
		PmiDatabase db = HandlerSession.getDatabase();
		
		Member author = db.getMemberByMail(remoteId);
		if (author == null) {
			service.reply(message, "Activity must be set. Try: 'Set Activity: <Activity Name>'");
			return false;
		}
		
		String activityId = userSettings.getActivityId();
		if (activityId == null) {
			service.reply(message, "Activity must be set. Try: 'Set Activity: <Activity Name>'");
			return false;
		}
		
		DefaultTimeEntry timeEntry = new DefaultTimeEntry(issue, author);
		timeEntry.setWorkedTime(workedTime);
		timeEntry.setComment(userSettings.getIssueComment());
		timeEntry.setActivity(db.getActivity(activityId));
		
		return db.commitWork(timeEntry) != null;
	}

}
